<template>
  <div>
    <!-- 加载状态 -->
    <el-skeleton :loading="isLoading" row="4" :columns="4" style="margin: 20px 0;">
      <template #template>
        <div style="padding: 15px;">
          <div style="width: 100%; height: 200px; background: #f5f5f5; border-radius: 4px;"></div>
          <div style="height: 20px; background: #f5f5f5; margin: 15px 0; width: 80%;"></div>
          <div style="height: 20px; background: #f5f5f5; margin-bottom: 15px; width: 40%;"></div>
          <div style="height: 40px; background: #f5f5f5; width: 100%;"></div>
        </div>
      </template>
    </el-skeleton>

    <!-- 错误提示 -->
    <el-alert
      v-if="hasError"
      title="获取商品失败，请刷新页面重试"
      type="error"
      show-icon
    />

    <!-- 搜索和商品列表（加载完成且无错误时显示） -->
    <template v-if="!isLoading && !hasError">
      <!-- 分类筛选 -->
      <el-tabs v-model="activeCategory" @tab-change="handleSearch" style="margin-bottom: 20px;">
        <el-tab-pane label="全部商品" name="" />
        <el-tab-pane label="电子产品" name="electronic" />
        <el-tab-pane label="家居用品" name="home" />
        <el-tab-pane label="服装鞋帽" name="clothing" />
      </el-tabs>

      <!-- 搜索和价格筛选 -->
      <div style="margin: 20px 0; display: flex; gap: 10px; flex-wrap: wrap;">
        <el-input
          v-model="searchKey"
          placeholder="搜索商品名称..."
          style="width: 300px;"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" icon="Search" />
          </template>
        </el-input>

        <el-select v-model="priceRange" placeholder="价格筛选" @change="handleSearch">
          <el-option label="全部价格" value="" />
          <el-option label="0-100元" value="0-100" />
          <el-option label="100-300元" value="100-300" />
          <el-option label="300元以上" value="300+" />
        </el-select>
      </div>

      <h2 style="margin: 20px 0;">商品列表</h2>

      <!-- 无搜索结果 -->
      <template v-if="filteredProducts.length === 0">
        <el-empty description="未找到匹配的商品" />
      </template>

      <!-- 商品列表 -->
      <el-row :gutter="20" v-else>
        <el-col :span="6" v-for="product in filteredProducts" :key="product.id">
          <el-card
            :body-style="{ padding: '15px', position: 'relative' }"
            style="transition: transform 0.3s; cursor: pointer;"
            @mouseenter="hoveredId = product.id"
            @mouseleave="hoveredId = null"
            :class="{ 'hover-card': hoveredId === product.id }"
          >
            <!-- 库存标签 -->
            <el-badge
              v-if="product.stock <= 10 && product.stock > 0"
              value="库存紧张"
              type="warning"
              style="position: absolute; top: 10px; right: 10px;"
            />
            <el-badge
              v-if="product.stock === 0"
              value="已售罄"
              type="danger"
              style="position: absolute; top: 10px; right: 10px;"
            />

            <img
              :src="product.image"
              style="width: 100%; height: 200px; object-fit: cover; border-radius: 4px;"
              :alt="product.name"
            >
            <h3 style="margin: 15px 0 10px; font-size: 16px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
              {{ product.name }}
            </h3>
            <p style="color: #f56c6c; font-size: 18px; margin-bottom: 15px;">¥{{ product.price.toFixed(2) }}</p>
            <el-button
              type="primary"
              style="width: 100%;"
              @click="$router.push(`/product/${product.id}`)"
              :disabled="product.stock === 0"
            >
              {{ product.stock === 0 ? '已售罄' : '查看详情' }}
            </el-button>
          </el-card>
        </el-col>
      </el-row>
    </template>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { useStore } from '../store'
import { Search } from '@element-plus/icons-vue'

const store = useStore()
const isLoading = ref(true)
const hasError = ref(false)
const searchKey = ref('')
const priceRange = ref('')
const activeCategory = ref('')
const hoveredId = ref(null)

onMounted(async () => {
  try {
    isLoading.value = true
    await store.fetchProducts()
    hasError.value = false
  } catch (err) {
    hasError.value = true
    console.error('加载商品失败：', err)
  } finally {
    isLoading.value = false
  }
})

const filteredProducts = computed(() => {
  return store.products.filter(product => {
    // 搜索筛选
    const matchSearch = product.name.toLowerCase().includes(searchKey.value.toLowerCase())

    // 价格筛选
    let matchPrice = true
    if (priceRange.value) {
      const [min, max] = priceRange.value.split('-').map(Number)
      if (priceRange.value === '300+') {
        matchPrice = product.price >= 300
      } else {
        matchPrice = product.price >= min && product.price <= max
      }
    }

    // 分类筛选（假设商品有category字段）
    const matchCategory = !activeCategory.value || product.category === activeCategory.value

    return matchSearch && matchPrice && matchCategory
  })
})

const handleSearch = () => {
  // 触发computed重新计算
}
</script>

<style scoped>
.hover-card {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}
</style>
